import 'package:FineArt/components/horizon_scroll.dart';
import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/core/widget/grid/grid_item_photo.dart';
import 'package:FineArt/page/home/components/module_filter.dart';
import 'package:FineArt/page/imageview/ImagePreview.dart';
import 'package:FineArt/page/imageview/imageview.dart';
import 'package:FineArt/page/search/component/TextTagWidget.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class ModulePage extends StatefulWidget {
  final Module _module;

  ModulePage(this._module);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _ModulePageState(this._module);
  }
}

class _ModulePageState extends State<ModulePage> {
  final Module _module;

  EasyRefreshController _controller = EasyRefreshController();

  _ModulePageState(this._module);

  List<Category> default_categories = [];
  List<Resource> resources = [];
  int currentPage = 0;
  String currentPath = "";
  String currentFilter = "";
  int currentPid = 0;

  MoreFilterGroup filterGroupRoot;

  List<MoreFilterGroup> filterGroups = [];

  final int PAGE_SIZE = 15;

  void _get_default_categories() {
    ModuleApi().categories(_module.id, _module.id).then((res) {
      if (!this.mounted) return;
      setState(() {
        default_categories.clear();
        Category all = new Category(
            label: "全部", selected: true, path: _module.id.toString(), id: 0);
        default_categories.add(all);
        default_categories.addAll(res.data);
      });
    });
  }

  void _getAll() {
    resources.clear();
    currentPage = 0;
    currentPath = _module.id.toString();
    currentFilter = "";
    _nextPage(currentPath, currentFilter);
  }

  void _nextPage(String path, String filter) {
    // LogUtil.d(StackTrace.current);
    ModuleApi().search(path, filter, currentPage, PAGE_SIZE).then((res) {
      if (!this.mounted) return;
      setState(() {
        //这行代码很别扭，但是解决了可能是控件本身的一个bug，当不够一页数据时会重复加载两次
        if (resources.length < PAGE_SIZE && resources.length > 0) return;

        currentPage = res.data.pageIndex + 1;
        resources.addAll(res.data.list);
        _controller.finishLoad(success: true);
      });
    });
  }

  void on_categories_selected(Category category) {
    resources.clear();
    filterGroups.clear();
    currentPage = 0;
    currentPath = category.path;
    currentFilter = "";
    currentPid = category.id;
    _nextPage(currentPath, currentFilter);
    _controller.callRefresh();
  }

  void request_with_filter(String path, String filter) {
    //String _filter = Uri.encodeComponent(filter);
    resources.clear();
    filterGroups.clear();
    currentPage = 0;
    currentPath = path;
    currentFilter = filter;
    currentPid = currentPid;
    _nextPage(currentPath, currentFilter); //
    _controller.callRefresh();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    LogUtil.d("module_page initState");

    _getAll();
    _get_default_categories();
  }

  @override
  void didChangeDependencies() {
    LogUtil.d("module_page didChangeDependencies");
    super.didChangeDependencies();
  }

  bool isFilter = false;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    var width = MediaQuery.of(context).size.width * 0.88;
    return Scaffold(
        backgroundColor: Colors.white,
        body: Column(
          children: [
            Padding(
              padding: EdgeInsets.symmetric(vertical: 2, horizontal: 2),
              child: Row(
                children: [
                  isFilter
                      ? SizedBox(
                          width: width,
                        )
                      : MHorizontalContainer(
                          categories: isFilter ? [] : this.default_categories,
                          onTapItem: this.on_categories_selected,
                          width: width,
                          height: 30,
                        ),
                  SizedBox(
                    width: 6,
                  ),
                  InkWell(
                    child: Image.asset(
                      isFilter
                          ? "assets/images/icon_close.png"
                          : "assets/images/icon_more.png",
                      // fit: BoxFit.fill,
                      width: getPortraitSWidth(16.5),
                      height: getPortraitSHeight(16.5),
                    ),
                    onTap: () {
                      print("more click>>>>>>");
                      showMoreFilter();
                    },
                  )
                ],
              ),
            ),
            Expanded(child: _widget_grid()),
          ],
        ));
  }

  void showBottomModel() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        barrierColor: Colors.transparent,
        backgroundColor: Colors.white,
        elevation: 0,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(0), topRight: Radius.circular(0))),
        builder: (BuildContext context) {
          return FractionallySizedBox(
            heightFactor: 0.82,
            child: ModuleGroupFilter(
              filterGroups: filterGroups,
              confirmPress: ()=>_confirmAction(),
            ),
          );
        });
  }

  void showMoreFilter() {
    ModuleApi().moreFilters(_module.id, currentPid, currentPath).then((res) {
      if (res.code == 200) {
        setState(() {
          filterGroups.clear();
          if (res.data.group_items != null) {
            MoreFilterGroup root = res.data;
            filterGroups.add(root);
            root.level = filterGroups.length;
          }
          showBottomModel();
        });
      }
    });
  }

  Widget getEmptyWidget() {
    return Text("");
  }

  Widget _widget_grid() {
    double width = MediaQuery.of(context).size.width * 0.98;
    MaterialHeader header =
        MaterialHeader(completeDuration: new Duration(milliseconds: 100));
    return EasyRefresh.custom(
      controller: _controller,
      header: header,
      footer: MaterialFooter(),
      onRefresh: () async {},
      onLoad: () async {
        _nextPage(currentPath, currentFilter);
      },
      slivers: <Widget>[
        SliverPadding(
            padding: EdgeInsets.only(left: 3, right: 3),
            sliver: SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                mainAxisSpacing: 0,
                crossAxisSpacing: 0,
                childAspectRatio: 0.73,
              ),
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  //创建子widget
                  var resource = resources[index];
                  return GridItemPhoto(
                      url: resource.url,
                      width: width / 3,
                      height: width / (3 * 0.73),
                      onTap: () {
                        // ToastUtils.toast('${resource.url}/${resource.id}');
                        // ImageViewPage.JumpToImagePreview(resource, context);
                        ImagePreview.JumpToPreview(currentPage, currentPath, currentFilter, index, resources, context);
                      });
                },
                childCount: resources.length,
              ),
            )),

        //=====列表=====//
      ],
    );
  }

  // Widget moreFilter() {
  //   return Stack(
  //     children: [
  //       Positioned(
  //         child: moreFilterGroups(),
  //         top: 2,
  //         bottom: getPortraitSHeight(50),
  //         width: SizeConfig.screenWidth,
  //       ),
  //       Positioned(
  //         child: getBottom(),
  //         bottom: 0,
  //         width: SizeConfig.screenWidth,
  //       )
  //     ],
  //   );
  // }

  // Widget moreFilterGroups() {
  //   return Padding(
  //       padding: EdgeInsets.symmetric(
  //           vertical: getPortraitSHeight(5),
  //           horizontal: getPortraitSWidth(12.5)),
  //       child: ListView.builder(
  //           itemCount: filterGroups.length,
  //           itemBuilder: (BuildContext context, int index) {
  //             return filterGroupItem(index);
  //           }));
  // }

  // Widget filterGroupItem(index) {
  //   return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
  //     SizedBox(
  //       height: getPortraitSHeight(10),
  //     ),
  //     Row(
  //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //       children: [
  //         InkWell(
  //           onTap: () {
  //             LogUtil.d("fold>>>>>");
  //           },
  //           child: Text(
  //             filterGroups[index].group_label,
  //             style: TextStyle(
  //                 fontSize: setSp(18),
  //                 color: text_black,
  //                 fontWeight: FontWeight.bold),
  //           ),
  //         ),
  //         InkWell(
  //           child: Image.asset(
  //             "assets/images/icon_arrow_down.png",
  //             width: getPortraitSWidth(18),
  //             height: getPortraitSHeight(18),
  //           ),
  //           onTap: () {
  //             LogUtil.d("delete>>>>>");
  //             if (mounted) {
  //               setState(() {
  //                 // itemSearchList = [];
  //               });
  //             }
  //           },
  //         )
  //       ],
  //     ),
  //     SizedBox(
  //       height: getPortraitSHeight(14),
  //     ),
  //     Wrap(
  //       children: filterGroupItem_subItems(filterGroups[index]),
  //       alignment: WrapAlignment.start,
  //       spacing: getPortraitSWidth(8),
  //       runSpacing: getPortraitSHeight(16),
  //     )
  //   ]);
  // }

  // List<TextTagWidget> filterGroupItem_subItems(MoreFilterGroup group) {
  //   List<TextTagWidget> tList = [];
  //   if (group.group_items.isEmpty) return tList;
  //
  //   for (var i = 0; i < group.group_items.length; i++) {
  //     MoreFilter item = group.group_items[i];
  //     tList.add(TextTagWidget(
  //         text: item.label,
  //         color: item.selected ? Colors.white : text_black,
  //         bgColor: item.selected ? Colors.red : bg_input,
  //         textClick: (text) {
  //           if (item.selected) return;
  //           setState(() {
  //             for (MoreFilter _item in group.group_items) {
  //               _item.selected = false;
  //             }
  //             item.selected = true;
  //             if (!group.asFilterObject) {
  //               //如果时分类，选中时，动态改变下级内容，如果是标签，则不需要
  //               int levels = filterGroups.length;
  //               int current_level = group.level;
  //               if (levels > current_level) {
  //                 for (int i = 0; i < levels - current_level; i++) {
  //                   filterGroups.removeLast();
  //                 }
  //               }
  //             }
  //           });
  //
  //           if (item.children != null) {
  //             for (MoreFilter mf in item.children.group_items) {
  //               mf.selected = false;
  //             }
  //             filterGroups.add(item.children);
  //             item.children.level = filterGroups.length;
  //           } else if (item.filters != null) {
  //             for (Filter filter in item.filters) {
  //               //把filter当成MoreFilterGroup来展示
  //               List<MoreFilter> _moreFilters = [];
  //               for (String value in filter.values) {
  //                 MoreFilter mf = MoreFilter(label: value);
  //                 mf.selected = false;
  //                 _moreFilters.add(mf);
  //               }
  //               MoreFilterGroup _group = MoreFilterGroup(
  //                   group_label: filter.markname, group_items: _moreFilters);
  //               _group.asFilterObject = true;
  //               filterGroups.add(_group);
  //               _group.level = filterGroups.length;
  //             }
  //           }
  //         }));
  //   }
  //   return tList;
  // }

  resetAction() {
    setState(() {
      if (filterGroups.length > 0) {
        int c = filterGroups.length - 1;
        for (int i = 0; i < c; i++) {
          filterGroups.removeLast();
        }

        MoreFilterGroup g = filterGroups.first;
        for (int i = 0; i < g.group_items.length; i++) {
          g.group_items[i].selected = false;
        }
      }
    });
  }

  _confirmAction() {
    if (filterGroups.length > 0) {
      String path = "";
      String filter = "";
      for (int i = filterGroups.length - 1; i >= 0; i--) {
        MoreFilterGroup mfg = filterGroups[i];
        if (mfg.asFilterObject) {
          for (int j = 0; j < mfg.group_items.length; j++) {
            if (mfg.group_items[j].selected) {
              filter += mfg.group_items[j].label;
              filter += "|";
              break;
            }
          }
        } else {
          for (int j = 0; j < mfg.group_items.length; j++) {
            if (mfg.group_items[j].selected) {
              path = mfg.group_items[j].path;
              break;
            }
          }
          if (path.isNotEmpty) break;
        }
      }

      if (filter.endsWith("|")) {
        filter = filter.substring(0, filter.length - 1);
      }

      request_with_filter(path, filter);

      // ToastUtils.success(path + "~" + filter);
    }

    Navigator.of(context).pop();
  }

  // Widget getBottom() {
  //   return Row(
  //     children: [
  //       Expanded(
  //           child: FlatButton(
  //         onPressed: () {
  //           setState(() {
  //             if (filterGroups.length > 0) {
  //               int c = filterGroups.length - 1;
  //               for (int i = 0; i < c; i++) {
  //                 filterGroups.removeLast();
  //               }
  //
  //               MoreFilterGroup g = filterGroups.first;
  //               for (int i = 0; i < g.group_items.length; i++) {
  //                 g.group_items[i].selected = false;
  //               }
  //             }
  //           });
  //         },
  //         child: Text(
  //           "重置",
  //           style: TextStyle(fontSize: setSp(18), color: text_black),
  //         ),
  //         height: 49,
  //         color: bg_button_gray,
  //       )),
  //       Expanded(
  //           child: FlatButton(
  //         onPressed: () {
  //           if (filterGroups.length > 0) {
  //             String path = "";
  //             String filter = "";
  //             for (int i = filterGroups.length - 1; i >= 0; i--) {
  //               MoreFilterGroup mfg = filterGroups[i];
  //               if (mfg.asFilterObject) {
  //                 for (int j = 0; j < mfg.group_items.length; j++) {
  //                   if (mfg.group_items[j].selected) {
  //                     filter += mfg.group_items[j].label;
  //                     filter += "|";
  //                     break;
  //                   }
  //                 }
  //               } else {
  //                 for (int j = 0; j < mfg.group_items.length; j++) {
  //                   if (mfg.group_items[j].selected) {
  //                     path = mfg.group_items[j].path;
  //                     break;
  //                   }
  //                 }
  //                 if (path.isNotEmpty) break;
  //               }
  //             }
  //
  //             if (filter.endsWith("|")) {
  //               filter = filter.substring(0, filter.length - 1);
  //             }
  //
  //             request_with_filter(path, filter);
  //             Navigator.of(context).pop();
  //             setState(() {
  //               this.isFilter = false;
  //             });
  //             //ToastUtils.success(path + "~" + filter);
  //           }
  //         },
  //         child: Text(
  //           "确定",
  //           style: TextStyle(fontSize: setSp(18), color: Colors.white),
  //         ),
  //         height: 49,
  //         color: red_main,
  //       )),
  //     ],
  //   );
  // }
}
